package com.atguigu.netty.udp;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

public class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket> {
    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
        ByteBuf content = msg.content();
        int i = content.indexOf(0, content.readableBytes(), LogEvent.SEPARATOR);
        String filename = content.slice(0, i).toString(CharsetUtil.UTF_8);
        String logMsg = content.slice(i + 1, content.readableBytes()).toString(CharsetUtil.UTF_8);

        LogEvent logEvent = new LogEvent(msg.recipient(), System.currentTimeMillis(), filename, logMsg);

        out.add(logEvent);


    }
}
